package com.gec.anan.customer.service.impl;

import com.gec.anan.common.constant.RedisConstant;
import com.gec.anan.common.execption.AnanException;
import com.gec.anan.common.result.Result;
import com.gec.anan.common.result.ResultCodeEnum;
import com.gec.anan.customer.client.CustomerInfoFeignClient;
import com.gec.anan.customer.service.CustomerService;
import com.gec.anan.model.form.customer.UpdateWxPhoneForm;
import com.gec.anan.model.vo.customer.CustomerLoginVo;
import com.gec.anan.model.vo.driver.DriverLoginVo;
import com.mysql.cj.protocol.x.StatementExecuteOk;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class CustomerServiceImpl implements CustomerService {

    @Autowired
    private CustomerInfoFeignClient client;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 小程序授权登录
     * @param code
     * @return
     */

    @Override
    public String login(String code) {
        //远程调用获取返回结果
        Result<Long> result = client.getCustomerId(code);
        //判断状态码信息
        if(result.getCode().intValue() != 200){
            throw new AnanException(result.getCode(), result.getMessage());
        }
        //判断id是否存在
        Long customerId = result.getData();
        if(customerId ==null){
            throw new AnanException(ResultCodeEnum.DATA_ERROR);
        }
        //生成token
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        log.info("token=>{}", token);

        //存放到redis
        redisTemplate.opsForValue().set(RedisConstant.USER_LOGIN_KEY_PREFIX+token, customerId.toString(),
                RedisConstant.USER_LOGIN_KEY_TIMEOUT, TimeUnit.SECONDS );

        return token;
    }

    @Override
    public CustomerLoginVo getCustomerInfo(Long customerId) {
        //远程调用
        Result<CustomerLoginVo> result = client.getCustomerInfo(customerId);
        //判断状态码
        if(result.getCode().intValue() !=200){
            throw new AnanException(result.getCode(),result.getMessage());
        }
        //判断数据是否存在
        CustomerLoginVo customerInfo = result.getData();
        if(customerInfo == null){
            throw new AnanException(ResultCodeEnum.DATA_ERROR);
        }
        //返回用信息
        return customerInfo;
    }

    @Override
    public Boolean updateWxPhoneNumber(UpdateWxPhoneForm updateWxPhoneForm) {
        return client.updateWxPhoneNumber(updateWxPhoneForm).getData();
    }


}
